ValidationViewModelBase.cs
Language: C#
Last Modified: 2020-06-27 1:58:36 PM UTC
File Size: 2718 bytes
Last Modified: 2020-06-27 1:58:36 PM UTC
File Size: 2718 bytes
http://www.penguinstew.ca/example/MVVMbase/ViewModelBase/ValidationViewModelBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace Penguin.MVVMBase.ViewModelBase
{
/// <summary>
/// Base for ViewModel with Validation
/// </summary>
public class ValidationViewModelBase : ViewModelBase, IDataErrorInfo
{
#region Fields
/// <summary>
/// Dictionary of validation functions mapped to property names
/// </summary>
private Dictionary<string, Func<string>> m_validationFunctions = new Dictionary<string, Func<string>>();
#endregion
#region IDataErrorInfo
/// <summary>
/// Returns an error message for the whole view model
/// </summary>
public string Error
{
get { return String.Empty; }
}
/// <summary>
/// Returns error message for the given item
/// </summary>
/// <param name="columnName">The item to validate</param>
/// <returns>Empty string if valid, error message otherwise</returns>
public string this[string columnName]
{
get {
Func<string> validationFunction;
if (m_validationFunctions.TryGetValue(columnName, out validationFunction))
{
return validationFunction();
}
else
{
return string.Empty;
}
}
}
#endregion
/// <summary>
/// Tests if all properties on this view model are valid
/// </summary>
/// <returns>True if valid, false otherwise</returns>
protected bool IsValid()
{
bool isValid = m_validationFunctions.All(v => String.IsNullOrEmpty(v.Value()));
return isValid;
}
/// <summary>
/// Adds the given validation function for the given property
/// </summary>
/// <param name="propertyName">Name of the property being validated</param>
/// <param name="validationFunction">The function to validate the property</param>
protected void AddValidation(string propertyName, Func<string> validationFunction)
{
//Test propertyName to make sure it's a valid property
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName;
throw new ArgumentException(msg);
}
m_validationFunctions.Add(propertyName, validationFunction);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85